package com.smallpineapple.turing.exception;

import com.smallpineapple.turing.util.JsonResultUtil;
import com.smallpineapple.turing.enums.MyCustomizeErrorCode;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;

/**
 * @author Jack
 * @date 2019-07-27-18:34
 */
@ControllerAdvice
public class MyCustomizeExceptionHandler implements CustomizeExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    @Override
    public JsonResultUtil handleCustomizeException(HttpServletRequest request, Throwable ex) {

        //获取错误状态码
        HttpStatus status = getStatus(request);
        if (ex instanceof CustomizeException) {
            CustomizeException customizeException = (CustomizeException) ex;
            JsonResultUtil jsonResultUtil = JsonResultUtil.errorOf(customizeException.getCode(), customizeException.getMessage());
            System.out.println(jsonResultUtil.toString());
            return jsonResultUtil;
        }

        if (status.is5xxServerError() || ex instanceof ParseException) {
            JsonResultUtil jsonResultUtil = JsonResultUtil.errorOf(MyCustomizeErrorCode.INTERNAL_SERVER_ERROR);
            return jsonResultUtil;
        }

        return null;

    }

    @ExceptionHandler(MultipartException.class)
    @ResponseBody
    @Override
    public JsonResultUtil handleMultipartException() {
        JsonResultUtil jsonResultUtil = JsonResultUtil.errorOf(MyCustomizeErrorCode.FILE_MAX_SIZE_EXCEPTION);
        return jsonResultUtil;
    }

    private HttpStatus getStatus(HttpServletRequest request) {

        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);

    }

}
